package sound;

import java.util.ArrayList;
import java.util.List;

import org.newdawn.slick.Music;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.Sound;

public class SoundManager {

	public static Sound simpleShot;
	public static Sound playerExplosion;
	public static Sound simpleBullet;
	public static Sound waveComplete;

	public static List<Sound> enemyExplosions;
	public static List<Sound> bulletRiochets;

	public static Music mainTheme;
	public static Music bossTheme;
	public static Music victory;

	private Music currentlyPlayed;
	private float volume;

	public static void loadFiles() {
		try {

			simpleShot = new Sound("res/underwater_laser.ogg");
			playerExplosion = new Sound("res/explosion_01.ogg");
			waveComplete = new Sound("res/wave_complete.ogg");
			mainTheme = new Music("res/bg_track.ogg");
			bossTheme = new Music("res/boss_track.ogg");
			victory = new Music("res/Jam_you_won.ogg");

			enemyExplosions = new ArrayList<Sound>();
			enemyExplosions.add(new Sound("res/explosion_01.ogg"));
			enemyExplosions.add(new Sound("res/explosion_02.ogg"));
			enemyExplosions.add(new Sound("res/explosion_03.ogg"));

			bulletRiochets = new ArrayList<Sound>();
			bulletRiochets.add(new Sound("res/bullet_ricochet_01.ogg"));
			bulletRiochets.add(new Sound("res/bullet_ricochet_02.ogg"));
			bulletRiochets.add(new Sound("res/bullet_ricochet_03.ogg"));
			bulletRiochets.add(new Sound("res/bullet_ricochet_04.ogg"));

		} catch (SlickException e) {
			e.printStackTrace();
		}
	}

	private static SoundManager instance;

	private SoundManager() {
		volume = 0.6f;
	}

	public static SoundManager getSoundManager() {
		return instance == null ? instance = new SoundManager() : instance;
	}

	public void playMusic(Music music) {
		if (currentlyPlayed == music) {
			return;
		}
		if (currentlyPlayed != null) {
			if (currentlyPlayed.playing()) {
				currentlyPlayed.fade(300, 0.1f, true);
			}
		}
		currentlyPlayed = music;
		music.loop();
		music.setVolume(volume);
	}

	public void pause() {
		if (currentlyPlayed != null) {
			currentlyPlayed.fade(300, 0.0f, false);
			currentlyPlayed.pause();
		}
	}
	
	public void stop() {
		if (currentlyPlayed != null) {
			currentlyPlayed.stop();
		}
 	}

	public void resume() {
		if (currentlyPlayed != null) {
			currentlyPlayed.resume();
		}
	}

	public void setVolume(float volume) {
		this.volume = volume;
		if (currentlyPlayed != null) {
			currentlyPlayed.setVolume(volume);
		}
	}

	public Sound getExplosionSound() {
		int i = (int) (Math.random() * 3);
		return enemyExplosions.get(i);
	}

	public Sound getBulletSound() {
		int i = (int) (Math.random() * 4);
		return bulletRiochets.get(i);
	}

	public void playSound(Sound sound, float pitch) {
		sound.play(pitch, .1f);
	}

}
